﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ClassLibrary1.entity
{
    [XmlRoot("cargo")]
   public class Cargo: BaseEntity
    {
       [XmlElement("ins")]
       public Insurance insurance { get; set; }

       [XmlElement("book")]
       public Booking booking { get; set; }

       [XmlElement("client")]
       public Client client { get; set; }
        
        public Cargo()
        {
            int id = 1;

            while (true)
            {
                var entity = FindById(id.ToString());
                if (entity == null)
                {
                    this.id = id;
                    return;
                }
                id++;
            }
        }
        
       public Cargo(string id) 
        {
            if (Cargo.FindById(id) != null) return;
            int.TryParse(id, out this.id);
        }

       public Cargo(string[] mas)
       {
           this.id = new Cargo(mas[0]).id;
           Upd(mas.Skip(1).ToArray());
       }

       public static Cargo FindById(string id)
       {
           return (Cargo)Data.entity.FirstOrDefault(item => item.GetType() == typeof(Cargo) && item.id == int.Parse(id));
       }

       public static List<BaseEntity> FindAll()
       {
           return Data.entity.FindAll(item => item.GetType() == typeof(Cargo));
       }

       public override void Upd(string[] mas)
       {
           try
           {
               this.client = Client.FindById(mas[0]);
               if (this.client != null) this.client.cargo = this;
           }
           catch (Exception) { }
           try { 
               this.booking = Booking.FindById(mas[1]);
               if (this.booking != null) this.booking.cargo = this;
           }
           catch (Exception) { }
           try { 
               this.insurance = Insurance.FindById(mas[2]);
               if (this.insurance != null) this.insurance.cargo = this;
           }
           catch (Exception) { }
           
       }

       public bool Equals(Booking a)
       {
           if (this.id.Equals(a.id)) return true;
           return false;
       }

       public override string Write()
       {
           string s = "cargo" + " " + this.id;
           s += " ";
           if (this.client != null) s += this.client.id.ToString();
           s += " ";
           if (this.booking != null) s += this.booking.id.ToString();
           s += " ";
           if (this.insurance != null) s += this.insurance.ToString();
           return s;
       }
    }
}
